import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';
import 'package:vape_xe/values/values.dart';

class PlayGroundController extends GetxController with GetTickerProviderStateMixin {
  /// 响应式成员变量
  final playGroundData = <String, dynamic>{}.obs;
  final productList = [].obs;

  /// 成员变量
  late TabController tabController;
  final TextEditingController textEditingController = TextEditingController();

  final double _targetPosition = 110; // 文字滑动到的目标位置
  final List<PaoPaoPage> paoPaoList = [];

  // 浮动位置,按左右左右来排序，如果低于5个，可随机index
  final y = [230, 200, 400, 440, 560];
  final x = [73, 42, 22, 22, 220];

  //泡泡按钮动画
  late AnimationController buttonAnimationController;
  late Animation animation1;
  late Animation animation2;
  late Animation animation3;
  late Animation animation4;

  /// 事件
  void onUpgradeTap() {
    if (productList.isEmpty) return;
    Get.toNamed(Routes.ENERGY, arguments: {
      'type': productList[tabController.index]['type'],
      'modelNum': productList[tabController.index]['modelNum'],
    });
  }

  void onPopTap(int position, int index) async {
    PaoPaoPage page = paoPaoList[position];
    if (!page.isStopped[index]) {
      page.animationController[index].stop(); // 停止浮动动画
      var currentPosition = page.floatingAnimation[index].value;
      page.animationController[index].value = 0;

      //moveToPositionYAnimation之所以要再次定义，是因为需要从泡泡当前位置滚动
      page.moveToPositionYAnimation[index] = Tween<double>(begin: currentPosition, end: _targetPosition)
          .animate(CurvedAnimation(parent: page.animationController[index], curve: Curves.decelerate));
      page.animationController[index].animateTo(1, duration: const Duration(seconds: 1));
      page.animationController[index].addListener(() {
        if (page.animationController[index].isCompleted) {
          buttonAnimationController.stop();
          buttonAnimationController.value = 0;
          buttonAnimationController.forward();
        }
      });
    } else {
      page.animationController[index].repeat(reverse: true); // 恢复浮动动画
    }
    page.isStopped[index] = !page.isStopped[index];
  }

  void showPaoPao() {
    productList.forEach((e) {
      PaoPaoPage page = PaoPaoPage();
      page.animationController.clear();
      page.floatingAnimation.clear();
      page.moveToPositionYAnimation.clear();
      page.moveToPositionXAnimation.clear();
      page.opacityAnimation.clear();
      page.scaleAnimation.clear();
      List.generate(page.index.length, (position) {
        int index = page.index[position]; // 拿哪个位置
        page.isStopped.add(false);
        page.animationController.add(AnimationController(
          duration: const Duration(seconds: 2),
          vsync: this,
        ));
        page.floatingAnimation.add(Tween<double>(begin: y[index] - 20, end: y[index] + 20)
            .animate(CurvedAnimation(parent: page.animationController[position], curve: Curves.easeInOut)));
        page.moveToPositionYAnimation.add(Tween<double>(begin: 0, end: _targetPosition)
            .animate(CurvedAnimation(parent: page.animationController[position], curve: Curves.decelerate)));
        page.moveToPositionXAnimation.add(Tween<double>(begin: 1.0, end: 0.0)
            .animate(CurvedAnimation(parent: page.animationController[position], curve: Curves.decelerate)));
        page.opacityAnimation.add(Tween<double>(begin: 1.0, end: 0.0)
            .animate(CurvedAnimation(parent: page.animationController[position], curve: Curves.easeInQuint)));
        page.scaleAnimation.add(Tween<double>(begin: 1.0, end: 0.0)
            .animate(CurvedAnimation(parent: page.animationController[position], curve: Curves.easeInQuint)));
        Future.delayed(Duration(milliseconds: Random().nextInt(1000) + 100), () {
          page.animationController[position].repeat(reverse: true);
        });
      });

      paoPaoList.add(page);
    });
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    var playGroundDataOffline = StorageService.to.getString(STORAGE_PLAYGROUND_INFO);
    if (playGroundDataOffline.isNotEmpty) {
      playGroundData.value = jsonDecode(playGroundDataOffline);
      productList.value = playGroundData['productList'] ?? [];
      tabController = TabController(length: productList.length, vsync: this);

      showPaoPao();
    }

    buttonAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );
    animation1 = Tween(begin: 0.0, end: 0.6)
        .chain(CurveTween(curve: const Interval(0.0, 0.25)))
        .animate(buttonAnimationController);
    animation2 = Tween(begin: 0.6, end: 0.0)
        .chain(CurveTween(curve: const Interval(0.25, 0.5)))
        .animate(buttonAnimationController);
    animation3 = Tween(begin: 1.0, end: 0.0)
        .chain(CurveTween(curve: const Interval(0.5, 0.75)))
        .animate(buttonAnimationController);
    animation4 = Tween(begin: 0.0, end: 1.0)
        .chain(CurveTween(curve: const Interval(0.75, 1)))
        .animate(buttonAnimationController);

    ever(EventService.to.message, (message) async {
      if (message.startsWith(EventService.EventRefresh)) {
        await Request().get('/user/groundData').then((result) {
          playGroundData.value = result['result'];
          StorageService.to.setString(STORAGE_PLAYGROUND_INFO, jsonEncode(result['result']));
          productList.value = playGroundData['productList'] ?? [];
          tabController = TabController(initialIndex: tabController.index, length: productList.length, vsync: this);

          showPaoPao();
        });
      }
    });
  }

  @override
  void onReady() async {
    super.onReady();
    await Request().get('/user/groundData').then((result) {
      playGroundData.value = result['result'];
      StorageService.to.setString(STORAGE_PLAYGROUND_INFO, jsonEncode(result['result']));
      productList.value = playGroundData['productList'] ?? [];
      tabController = TabController(length: productList.length, vsync: this);

      showPaoPao();
    });
  }
}

class PaoPaoPage {
  PaoPaoPage() {
    final random = Random();
    final count = random.nextInt(3) + 3; // 页面随机3到5个泡泡
    final Set<int> selectedNumbers = {};
    while (selectedNumbers.length < count) {
      selectedNumbers.add(random.nextInt(5)); // 生成 0 到 4 之间的随机数
    }
    // 将 Set 转换为 List 并排序
    index = selectedNumbers.toList()..sort();
  }

  final List<bool> isStopped = [];
  final List<AnimationController> animationController = [];
  final List<Animation<double>> floatingAnimation = []; // 控制上下浮动的动画
  final List<Animation<double>> moveToPositionYAnimation = []; // 控制滑动到目标位置的动画Y
  final List<Animation<double>> moveToPositionXAnimation = []; // 控制滑动到目标位置的动画X
  final List<Animation<double>> opacityAnimation = []; // 控制透明度的动画
  final List<Animation<double>> scaleAnimation = []; // 控制缩放的动画
  late List<int> index; // 随机泡泡
}
